const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const uuid = require("uuid");
const cors = require("@koa/cors");

const app = new Koa();
const router = new Router();

app.use(
    cors({
        origin: "http://127.0.0.1:5500", // 前端地址
        credentials: true,
    })
);
app.use(bodyParser());
app.keys = ["ya"];

const session = {}; // 用来存储用户和信息的映射关系，对浏览器不可见;通常存在redis里面
const cardName = "connect_sig";
router.post("/login", async (ctx, next) => {
    let { username, password } = ctx.request.body;
    if (username == "admin" && password == "admin") {
        let cardId = uuid.v4();
        session[cardId] = { username };

        ctx.cookies.set(cardName, cardId, { httpOnly: true }); // cookie中只存一个标识，并没有真实的数据
        ctx.body = {
            code: 200,
            data: {
                username,
            },
        };
    }
});
router.get("/user", async (ctx, next) => {
    let id = ctx.cookies.get(cardName);
    if (id && session[id]) {
        username = session[id].username;
        ctx.body = {
            code: 200,
            data: {
                username,
            },
        };
    } else {
        ctx.body = {
            code: 401,
            data: "cookies已失效",
        };
    }
});

app.use(router.routes());
app.listen(3000);
